<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Home\Controller;
use Home\Controller\CommonController;
use Think\Page;

/**
 * Description of ImgController
 *
 * @author Rung-PC
 */
class ImgController extends CommonController{
    //put your code here
    public function indeximg()
    {
        $this->display();
    }
    
    public function show()
    {
        $user_id = session('user_id');
        $id_name = I('id_name');
        $id_card = I('id_card');
        if(IS_POST){
            if(!empty($id_card)){
                $map['id_card'] = $id_card;
            }else{
                 $map['id_name'] = $id_name;
            }       
        }
        $map['user_id'] = $user_id;
        $img = D('AdminUser');
        $totalRows = $img->countAll('img',$map);        //var_dump($totalRows);die;
        $page = new Page($totalRows,5);
        $result = $img->select('img',$map,$field='',$order='id desc',$page->firstRow,$page->listRows);     //   var_dump($result);die;
        $this->assign('page',$page->show());
        $this->assign('result',$result);
        $this->display();
    }
    
    public function uploadimg()
    {       
        if(!empty($_FILES))
        {       
        $maxSize = $_FILES['positive']['size']+$_FILES['opposite']['size'];        //dump($maxSize);die;
        if($maxSize > 409600)
        {
            $this->error('图片尺寸应小于400kb');
        }
        $imgages = ['image/jpeg','image/png','image/jpg'];
        if(!in_array($_FILES['positive']['type'], $imgages) || !in_array($_FILES['opposite']['type'], $imgages))
        {
            $this->error('格式文件非法!');
        }
        $user_id = session('user_id');
        if(empty($user_id))
        {
            $this->error('非法用户!');
        }
        $user_dir = "./Public/images/idphoto2/".$user_id.'/';       // dump($user_dir);die;
        if(!file_exists($user_dir))
        {
            $this->create_dirs($user_dir);
        }
        $id_card = I('id_card');
        $positive_name = $id_card.'_1.jpg';
        $opposite_name = $id_card.'_2.jpg';
        $positive = move_uploaded_file($_FILES['positive']['tmp_name'], $user_dir.$positive_name);
        $opposite = move_uploaded_file($_FILES['opposite']['tmp_name'], $user_dir.$opposite_name);
        
        if($positive && $opposite)
        {
        $id_name = I('id_name');
        
        $img = D('AdminUser');
                
        $data['user_id'] = $user_id;;
        $data['id_name'] = $id_name;
        $data['id_card'] = $id_card;
        $data['positive'] = $positive_name;
        $data['opposite'] = $opposite_name;
        
        $info = $img->find('img',['id_card'=>$id_card]);        //var_dump($info);die;
        if(empty($info))
        {
            $result = $img->insertOne('img',$data);
            if($result)
            {
                $this->error('添加成功!');
            }
            unlink($user_dir.$positive_name);
            unlink($user_dir.$opposite_name);
            $this->error('添加失败!');
        }else{
            $result = $img->change('img',['id'=>$info['id']],$data);            //var_dump($result);die;
            if($result)
            {
                unlink($user_dir.$info['positive']);
                unlink($user_dir.$info['opposite']);
                $this->error('更新成功!');
            }
            unlink($user_dir.$positive_name);
            unlink($user_dir.$opposite_name);
            $this->error('更新失败!');
        }
        }
        }
    }
    
    public function idDown(){
           if(!empty($_FILES)){
                $subName = $this->guid();
                $info = $this->upload(['xlsx'],'/xlsx/',$subName);
                 vendor("PHPExcel.PHPExcel");
                $file_name='./Uploads'.$info['import']['savepath'].$info['import']['savename'];
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
                $sheet = $objPHPExcel->getSheet(0);                //dump($sheet);exit;
                $highestRow = $sheet->getHighestRow(); // 取得总行数

                $userInfo = [];
                if($highestRow > 3){
                    for($i=2;$i<=$highestRow;$i++){   
                        $userInfo[] =['idcard'=>trim($objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue())];
                    } 
                }
//                dump($userInfo);
               if(empty($userInfo)){
                   $this->delDirAndFile("./Uploads/xlsx/".$subName."/");
                   $this->error('three.xlsx文件无有效内容!');
               } 
               
               $cry = [];
                    foreach ($userInfo as $key=>$v){                                     //去除重复
                        if((in_array(strtolower($v['idcard']),$cry) && !empty($v['idcard'])) || (in_array($v['idname'],$cry) && !empty($v['idname'])) ){
                           unset($userInfo[$key]);
                       }else{
                           $cry[] = strtolower($v['idcard']);
                            $cry[] = $v['idname'];
                       }
                    }
               
               $admin_user = D('AdminUser');
               $exportInfo = [];
//               dump($userInfo);
               foreach ($userInfo as $value) {                     
                        $cardResult = $admin_user->find('img',['id_card'=>$value['idcard']]);                      //dump($cardResult);
                       if(!empty($cardResult)){
                            $exportInfo[] = $cardResult;                   
                    }
               }
//               dump($exportInfo);
        if(empty($exportInfo)){
            $this->delDirAndFile("./Uploads/xlsx/".$subName."/");
            $this->error('无匹配数据!');
        }       
               
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);  
        $objActSheet = $objPHPExcel->getActiveSheet();
        
        // 水平居中（位置很重要，建议在最初始位置）
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);   
        
        $objActSheet->setCellValue('A1', '姓名');
        $objActSheet->setCellValue('B1', '身份证号码');
        
        // 设置个表格宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(16);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        
        // 垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        
        // 处理表数据
        $images = [];
        $order_goods = [];
        $user_id = session('user_id');
//        $user_name = session('user_name');
        foreach($exportInfo as $k=>$v){
            $k +=2;
            $objActSheet->setCellValue('A'.$k, $v['id_name']);    
            $objActSheet->setCellValue('B'.$k, ' '.$v['id_card']); 
            $images[] = $v['positive'];        
            $images[] = $v['opposite'];          

            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20); 
//            if($user_id != 1 && $user_name != 'admin'){           
//                $recordResult = $admin_user->find('record',['user_id'=>$user_id,'idcard'=>$v['idcard']]);
//                if(empty($recordResult) && $v['idname'] != null && $v['idcard']!= null){
//                    $record_id = $admin_user->insertOne('record',['user_id'=>$user_id,'idname'=>$v['idname'],'idcard'=>$v['idcard'],'num'=>1]);
//                    $order_goods[] = $record_id;
//                }else{
//                    $admin_user->plus('record',['id'=>$recordResult['id']],'num',1);
//                }
//            }
        }
//        if($user_id != 1 && $user_name != 'admin'){
//            if(!empty($order_goods)){
//                $order_sn = $this->get_order_sn();
//                $total_price = count($order_goods)*3;
//                $order_id = $admin_user->insertOne('order_info',['user_id'=>$user_id,'user_name'=>$user_name,'order_sn'=>$order_sn,'order_status'=>0,'total_price'=>$total_price,'addtime'=> time()]);
//                foreach ($order_goods as $id) {
//                    $admin_user->update('record',['id'=>$id],'order_id',$order_id);
//                }
//            }
//        }
//        dump($images);
        $rand = $this->guid();
        $dir = './Uploads/temp/'. $rand.'/';
        $this->create_dirs($dir);
        if(!empty($images)){
            foreach ($images as $img) {
                copy("./Public/images/idphoto2/". $user_id."/".$img, $dir.$img);                                           //复制图片到指定目录准备打包
            }
        }
//        dump($images);     
        
        $fileName = '身份信息表';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xlsx";
        $fileName = iconv("utf-8", "gb2312", $fileName);;
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);

        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');        //dump($objWriter);
        $objWriter->save($dir.$fileName);                       //生成的Execl表格移動到指定目錄
        $this->delDirAndFile("./Uploads/xlsx/".$subName."/");
        
                  vendor('FileToZip.FileToZip');
                  $handler = opendir($dir);    //$cur_file 文件所在目录
                  $download_file = array();
                  $i = 0;
                  while( ($filename = readdir($handler)) !== false ) {
                      if($filename != '.' && $filename != '..') {
                          $download_file[$i++] = $filename;
                      }
                  }
                  closedir($handler);
                  $scandir=new \traverseDir($dir,'./Uploads/');    //$save_path zip包文件目录
                  $scandir->tozip($download_file,$dir);
        } else {
            $this->error('请选择上传文件!');
        }   
    }


    public function del(){
        $id = I('id');
        if(empty($id)){
            return;
        }
        $img = D('AdminUser');
        $result = $img->del('img',['id'=>$id]);
        if($result){
            $user_id = I('user_id');
            $positive = I('positive');
            $opposite = I('opposite');
            $user_dir = "./Public/images/idphoto2/".$user_id.'/'; 
            unlink($user_dir.$positive);
            unlink($user_dir.$opposite);
            $this->ajaxReturn(['status'=>1,'message'=>'删除成功']);
        }
    }
   
}
